package com.army.study;

import com.army.study.utils.HPermission;
import com.army.study.utils.JSInterface;
import ohos.ace.ability.AceAbility;
import ohos.aafwk.content.Intent;
import ohos.ace.ability.LocalParticleAbility;
import ohos.distributedhardware.devicemanager.DeviceManager;

public class MainAbility extends AceAbility {
    private HPermission permission;
    private JSInterface jsInterface;

    // 需要在线程中调用。
    private LocalParticleAbility.Callback callback;
    /**
     * 设置异步JS回调接口。
     * @param back
     */
    public void setCallback(final LocalParticleAbility.Callback back) {
        this.callback = back;
    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        jsInterface = new JSInterface(this);
        jsInterface.register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        jsInterface.deregister(this);
    }

    /**
     * 请求权限并获取本地网络ID。
     */
    public void requestPermissionAndGetNetWorkId() {
        permission = new HPermission();
        permission.requestPermissions(this, this::getNetWorkId);
    }

    /**
     * 获取本地NetWorkId并将其返回给JS。
     * 需要通过获取网络ID。
     * DeviceManager.DeviceManager回调。
     */
    private void getNetWorkId() {
        DeviceManager.createInstance(new DeviceManager.DeviceManagerCallback() {
            @Override
            public void onGet(DeviceManager deviceManager) {
                // 获取本地设备Id
                String networkId = deviceManager.getLocalDeviceInfo().getNetworkId();
                jsCallBack(networkId);
            }

            @Override
            public void onDied() {

            }
        });
    }

    private void jsCallBack(final String networkId) {
        if (callback != null) {
            // 多线程启动回调本地设备Id
            new Thread(() -> callback.reply(networkId)).start();
        }
    }

    /**
     * 来自用户请求的权限请求结果
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
//        super.onRequestPermissionsFromUserResult(requestCode, permissions, grantResults);
        if (permission != null) {
            permission.onRequestPermissionsFromUserResult(requestCode, grantResults);
        }
    }

    /**
     * 启动远程功能。
     * @param type
     */
    public void isAllowGameAsync(final int type) {
        permission = new HPermission();
        permission.requestPermissions(this, ()->{
            if (callback != null) {
                new Thread(()-> callback.reply(type)).start();
            }
        });
    }

}
